import { Button } from "antd";
import Recorder from "js-audio-recorder";
import { useEffect, useState } from "react";

const Record: React.FC = (props: any) => {
  const {} = props;
  const [time, setTime] = useState<any>();
  const [active, setActive] = useState(false);
  const [drawId, setDrawId] = useState<any>();
  const [isRecord, setIsRecord] = useState<any>(false);
  const startRecording = () => {
    if (!active) return;
    console.log("sss", recorderEx);

    recorderEx?.start().then(() => {
      drawRecord();
      setIsRecord(true);
      recorderEx.onprogress = function (params) {
        console.log("录音时长(秒)", params.duration);
        setTime(params.duration.toFixed(2));
      };
    }); // 开始录音
  };
  const stopRecording = () => {
    if (!active) return;
    recorderEx?.stop(); // 停止录音
    drawId && cancelAnimationFrame(drawId);
    setDrawId(null);
    const wavBlob = recorderEx?.getWAVBlob(); // blob格式
    console.log("lll", wavBlob);
    let filename = "音频";
    const file = new File([wavBlob], filename, {
      type: "application/json",
      lastModified: Date.now(),
    });
    console.log("file", file);
    const formData = new FormData();
    formData.append("files", file);
    formData.append("shipId", "1");
    recorderEx.downloadPCM("aa");
    // axios.post("http://192.168.3.25:8131/hikCarmeras/sendVoice", formData);
  };
  const [recorderEx] = useState<Recorder>(
    new Recorder({
      sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
      sampleRate: 8000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
      numChannels: 1, // 声道，支持 1 或 2， 默认是1
    })
  );

  const [canvas, setCanvas] = useState<any>();

  if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    try {
      (async () => {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: false,
          audio: true,
        });
        setActive(stream.active);
      })();
    } catch (err) {
      console.log(err);
    }
  } else {
    alert("没有麦克风配置");
  }
  useEffect(() => {
    let canvas = document.querySelector("#playChart")!;
    setCanvas(canvas);
  }, []);

  const drawRecord = () => {
    const id = requestAnimationFrame(drawRecord);
    setDrawId(id);
    let dataArray = recorderEx.getRecordAnalyseData();

    let bufferLength = dataArray.length;
    const ctx = canvas.getContext("2d");
    ctx.fillStyle = "rgba(200 , 200 ,200)";
    ctx.lineWidth = 2;
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.beginPath();
    ctx.strokeStyle = "green";
    const sliceWidth = (canvas.width * 1.0) / bufferLength; // 一个点占多少位置，共有bufferLength个点要绘制
    let x = 0; // 绘制点的x轴
    for (var i = 0; i < bufferLength; i++) {
      var v = dataArray[i] / 128.0;
      var y = (v * canvas.height) / 2;
      ctx.fillStyle = "red";
      if (i === 0) {
        // 第一个点
        ctx.moveTo(x, y);
      } else {
        // 剩余的点
        ctx.lineTo(x, y);
      }
      // 依次平移，绘制所有点
      x += sliceWidth;
    }

    ctx.lineTo(canvas.width, canvas.height / 2);
    ctx.stroke();
  };
  return (
    <>
      {isRecord ? (
        <Button>正在录音</Button>
      ) : (
        <Button onClick={startRecording}>开始录音</Button>
      )}
      <Button onClick={stopRecording}>结束录音</Button>
      <div>
        <div>时长:{time}</div>
        <canvas id="playChart"></canvas>
      </div>
    </>
  );
};

export default Record;
